app = @bhv
app.directive('waterBall', ->
  restrict: 'E'
  replace: true
  templateUrl: "views/chart/water-ball.html"
  scope:  color: '@', data: '@', icon: '@', iconText: '@'
  link: ($scope, element, attrs)->
    $root = $(element)
    $wave = $root.find('.wave')
    $shade = $root.find('.ball')
    ctx = null
    data = $scope.data

    buildWave = (width, height, transformY, transformX = 0)->
      waveWidth = width/2
      f = getWaveFunc(10, waveWidth, transformX, transformY)
      ctx.clearRect(0, 0, width, height)
      ctx.beginPath()
      for x in [0..width]
        ctx.lineTo(x, f(x))
      ctx.lineTo(width, height)
      ctx.lineTo(0, height)
      ctx.lineTo(0, f(0))
      ctx.fill()
      ctx.stroke()

      if transformX < waveWidth
        transformX = transformX + 1
      else
        transformX = 0

      setTimeout(
          ()-> buildWave(width, height, transformY, transformX)
        , 50
      )

    ###
      @waveHeight 波高（波峰和波谷的差距）
      @waveWidth 一个完整的波的宽度[0, 2π]
      @transformX, transformY  平移量 []
    ###
    getWaveFunc = (waveHeight, waveWidth, transformX = 0, transformY = 0)->
      (x)-> (waveHeight / 2) * Math.sin( (x + transformX)* (2*Math.PI/waveWidth)) + transformY

    setStyle = (cxt)->
      cxt.fillStyle = $scope.color
      cxt.strokeStyle = $scope.color

    buildBall = (width, height)->
      shadeWidth = if width > height then height else width
      $shade.css('width', shadeWidth + "px")
      $shade.css('height', shadeWidth + "px")
      R = Math.sqrt(Math.pow(width/2, 2) + Math.pow(height/2, 2))
      dRr = R - shadeWidth/2 + 5
      $shade.css('border', dRr + "px solid #0F131E")
      $shade.css('left', "-" + (dRr - Math.abs(width - height)/2)+ "px")
      $shade.css('top', "-" + dRr+ "px")

    buildIcon = (width, height)->
      return if not $scope.icon
      icon = $scope.icon
      iconEle = $("
        <span>
          <strong>#{$scope.iconText}</strong><br>
          <i class='icon-#{icon}'></i>
        </span>")
      $root.append(iconEle)


    init = ->
      $wave.append($("<canvas></canvas>"))
      canvas = $wave.find('canvas')[0]
      width = canvas.width = $wave.width()
      height = canvas.height = $wave.height()
      ctx = canvas.getContext("2d")
      setStyle(ctx)
      transformY = (1-data) * height

      buildWave(width, height, transformY)
      buildBall(width, height)
      buildIcon(width, height)

    init()
)